import React, { PureComponent } from "react";
import { connect } from "dva";
import uniq from 'lodash/uniq';
import { Modal, Row, Col, Form, Input, Select, Icon, Button, message} from "antd";
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
// const confirm = Modal.confirm;

@connect(({ path, global }) => ({
  loading:path.loading,
  detaildata:path.detaildata,
  selectSource: global.selectSource
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class PathAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: [] ,
      imageUrl: null,
      loading_picupload: false
    }
  }

  componentDidMount() {
    // const { dispatch } = this.props;
    // 维保单位列表
    // dispatch({
    //   type: 'global/fetch_select_maintencompany',
    // });
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true && this.props.visible === false) {
      // 编辑时 读取详情
      if (nextProps.detailId && nextProps.detailId !== 0) {
          this.props.dispatch({
            type: "path/fetch_path_info",
            payload: {
              lineId: nextProps.detailId
            }
          }).then(() => {
            this.setState({
              fileList: this.props.detaildata.attaDatum || []
            });
          });
      }
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, detailId, devIds } = this.props;
        const action = detailId === 0 ? 'add' : 'edit';
        const putdevIds = devIds && devIds.length>0 ? uniq(devIds) : undefined;
        const lineId = detailId === 0 ? undefined : detailId;
        dispatch({
            type: `path/${action}_path`,
            payload: {
              ...values,
              devIds:putdevIds,
              lineId,
            }
          })
          .then(() => {
            this.handleReset();
            this.handleCancel();
            this.props.callback();
            message.success(detailId === 0 ? "路线已添加成功" : "路线已修改成功");
            // this.goBack();
          });
      }
    });
  }


  handleReset = () => {
    this.setState({
      fileList: [],
      imageUrl: null,
    })
    this.props.form.resetFields();
  };

  handleCancel = () => {
    this.handleReset();
    this.props.onCancel(false);
  };

  // showConfirm = () =>{
  //   confirm({
  //     title: '您是否要继续配置路线养护点?',
  //     content: '您也可以后续在路线管理列表中维护养护点',
  //     onOk() {
  //       return new Promise((resolve, reject) => {
  //         // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
  //         const { dispatch, location } = this.props;
  //         const detailInfoId = match.params.id;
  //         router.push({ pathname:`/equipment/spares/${detailInfoId}/${key}`,  query: { ...location.query}});
  //       }).catch(() => console.log('Oops errors!'));
  //     },
  //     onCancel() {},
  //   });
  //
  // }

  render() {
    const { visible, loading, detailId, detaildata, maintenanceId, selectSource } = this.props;
    const { imageUrl } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 }
    };

    // const formItemLayoutOne = {
    //   labelCol: { span: 2 },
    //   wrapperCol: { span: 22 }
    // };

    // console.log('maintenanceSateId',maintenanceId);




    return (
      <div>
        <Modal
          title={detailId === 0 ? "新增路线" : "编辑路线"}
          okText={detailId === 0 ? "提交" : "编辑"}
          visible={visible}
          onOk={this.handleSubmit.bind(this)}
          confirmLoading={loading.model_submit}
          onCancel={this.handleCancel}
          width={500}
        >
          <Form layout="horizontal">
            <Row gutter={24}>
              {/*
              <Col span={24}>
                <FormItem {...formItemLayout} label="路线编号" colon={false}>
                  {getFieldDecorator("lineCode", {
                    initialValue: detailId === 0 ? undefined : detaildata.lineCode,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入备件名称" />
                  )}
                </FormItem>
              </Col>
              */}


              <Col span={24}>
                <FormItem {...formItemLayout} label="路线名称" colon={false}>
                  {getFieldDecorator("lineName", {
                    initialValue: detailId === 0 ? undefined : detaildata.lineName,
                    rules: [
                      { required: true, message: "请输入路线名称" },
                    ]
                  })(
                    <Input placeholder="请输入备件名称" />
                  )}
                </FormItem>
              </Col>


              <Col span={24}>
                <FormItem {...formItemLayout} label="维保单位" colon={false}>
                  {getFieldDecorator("maintenanceId", {
                    initialValue: maintenanceId ? maintenanceId : detailId === 0 ? undefined : (detaildata.maintenanceId && detaildata.maintenanceId),
                    rules: [
                      { required: true, message: "请选择维保单位" },
                    ]
                  })(
                    <Select placeholder="请选择维保单位"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}
                            disabled={maintenanceId ? true : false}
                    >
                      {selectSource.maintenance && selectSource.maintenance.map(item => (
                        <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem {...formItemLayout} label="备注" colon={false}>
                  {getFieldDecorator("remarks", {
                    initialValue: detailId === 0 ? undefined : detaildata.remarks,
                    rules: [{ max: 500, message: "不超过500个字" }]
                  })(
                    <TextArea
                      placeholder="请输入备注内容"
                      autosize={{ minRows: 3, maxRows: 6 }}
                    />
                  )}
                </FormItem>
              </Col>

            </Row>
          </Form>

        </Modal>

      </div>
    );
  }
}
